package com.ylb.rent.filter;



import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import com.ylb.rent.constant.RequestConstant;
import com.ylb.rent.dao.RoleDao;
import com.ylb.rent.entity.Permission;
import com.ylb.rent.entity.vo.RoleVo;
import com.ylb.rent.service.IRoleService;
import com.ylb.rent.util.R;
import com.ylb.rent.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @AUTHOR:游李滨
 * @DATE:2023/6/28 11:48
 */
@Component
public class SecurityFilter extends OncePerRequestFilter {


    @Autowired
    TokenUtil tokenUtil;


    @Autowired
    IRoleService roleService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(RequestConstant.TOKEN_HEADER);

        if(!StrUtil.hasEmpty(token) && !StrUtil.hasBlank(token)){
            long userId=1;
            try {
                userId = tokenUtil.verify(token);
                request.getSession().setAttribute("userId",userId);
            } catch (Exception e) {
                e.printStackTrace();
            }

//        TODO 查询用户权限，并加入数组
            List<GrantedAuthority> authorityList = new ArrayList<>();
            RoleVo roleVo = roleService.getRoleByUserId(userId);
            List<Permission> permissionList = roleVo.getPermissionList();
            permissionList.forEach(permission -> {
                authorityList.add(new SimpleGrantedAuthority(permission.getPermission()));
            });

//        存权限
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userId,null,authorityList);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        }

        filterChain.doFilter(request,response);
    }

}
